package com.cysion.study.ui

import android.annotation.SuppressLint
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.text.format.DateFormat
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.other._setOnClickListener
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.ShowToast
import kotlinx.android.synthetic.main.activity_clockin_map.*
import java.lang.Double

class ClockinMapActivity : BaseActivity() {
    override fun getLayoutId(): Int = R.layout.activity_clockin_map

    private var mSensorManager: SensorManager? = null
    private var mBaiduMap: BaiduMap? = null
    private var locData: MyLocationData? = null
    private var speed=""

    override fun initView() {
        //speed 打卡进度 0.上班打卡 1.下班打卡
        speed = intent.getBundleExtra("key").getString("speed")
        darkTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("我要打卡")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        val sysTime = System.currentTimeMillis()//获取系统时间
        val sysTimeStr = DateFormat.format("HH:mm:ss", sysTime)//时间显示格式
        if (speed == "0") {
            tv_submit.text = "$sysTimeStr 上班打卡" //更新时间
        } else {
            tv_submit.text = "$sysTimeStr 下班打卡" //更新时间
        }
        TimeThread().start() //启动显示时间线程
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager// 获取传感器管理服务
        mBaiduMap = mapView.map
        // 开启定位图层
        mBaiduMap?.isMyLocationEnabled=true


        val ms = MapStatus.Builder().overlook(0f).zoom(15.0f).build()
       /* val u1 = MapStatusUpdateFactory.newMapStatus(ms)
        //        mBaiduMap.setMapStatus(u1);
        mBaiduMap?.animateMapStatus(u1)

        locData = MyLocationData.Builder().accuracy(UserCache.radius)
            // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(mCurrentDirection.toFloat()).latitude(java.lang.Double.parseDouble(UserCache.lat))
            .longitude(java.lang.Double.parseDouble(UserCache.lon)).build()
        mBaiduMap?.setMyLocationData(locData)*/

        val config = MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null)
        mBaiduMap?.setMyLocationConfiguration(config)
        val latLng = LatLng(Double.parseDouble(UserCache.lat), Double.parseDouble(UserCache.lon))
        val msu = MapStatusUpdateFactory.newLatLng(latLng)
        mBaiduMap?.animateMapStatus(msu)
        CLog.e("@@@@定位位置=" +UserCache.cacheAddress)
        if (TextUtils.isEmpty(UserCache.cacheAddress)) {
            tv_mylocation.text = "未获取定位位置"
        } else {
            tv_mylocation.text=UserCache.cacheAddress
        }
        tv_submit._setOnClickListener {
            var content = et_content.text.toString().trim()
            sendClock(content)
        }
    }


    private fun sendClock(content: String) {
        Alert.loading(self)
        ApiClient.api.clockIn(UserCache.token,content,UserCache.lon,UserCache.lat,UserCache.cacheAddress).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("打卡成功")
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }



    override fun onStop() {
        // 取消注册传感器监听
        mSensorManager?.unregisterListener(sensorEventListener)
        super.onStop()

    }
    override fun onResume() {
        super.onResume()
        mapView.onResume()
        // 为系统的方向传感器注册监听器
        mSensorManager?.registerListener(
            sensorEventListener,
            mSensorManager?.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_UI
        )
    }
    private var mCurrentDirection = 0
    private var lastX = 0.0
    //传感监听器
    internal var sensorEventListener: SensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(sensorEvent: SensorEvent) {
            //每次方向改变，重新给地图设置定位数据，用上一次onReceiveLocation得到的经纬度、精度
            val x = sensorEvent.values[SensorManager.DATA_X].toDouble()
            if (Math.abs(x - lastX) > 1.0) {// 方向改变大于1度才设置，以免地图上的箭头转动过于频繁
                mCurrentDirection = x.toInt()
                locData = MyLocationData.Builder().accuracy(UserCache.radius)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection.toFloat())
                    .latitude(java.lang.Double.parseDouble(UserCache.lat))
                    .longitude(java.lang.Double.parseDouble(UserCache.lon)).build()
                mBaiduMap?.setMyLocationData(locData)
            }
            lastX = x


        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {

        }
    }


    internal inner class TimeThread : Thread() {
        override fun run() {
            do {
                try {
                    Thread.sleep(1000)
                    val msg = Message()
                    msg.what = 1  //消息(一个整型值)
                    mHandler.sendMessage(msg)// 每隔1秒发送一个msg给mHandler
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

            } while (true)
        }
    }

    //在主线程里面处理消息并更新UI界面
    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    val sysTime = System.currentTimeMillis()//获取系统时间
                    val sysTimeStr = DateFormat.format("hh:mm:ss", sysTime)//时间显示格式
//                    tv_submit.text = "$sysTimeStr 上班打卡" //更新时间
                    if (speed == "0") {
                        tv_submit.text = "$sysTimeStr 上班打卡" //更新时间
                    } else {
                        tv_submit.text = "$sysTimeStr 下班打卡" //更新时间
                    }
                }
                else -> {
                }
            }
        }
    }
    override fun closeMvp() {
    }

}
